// modules/settingModule/pages/servesubmit/servesubmit.js
const db = wx.cloud.database();
const appUser = getApp();
const _ = db.command;

const app_id = "115945259";
const secret_key = "VvrpcgKnhMUDAHdXfTQ7NvlbPQt16Qrz"
const api_key = "APkJ8Ji06DAoFOzExRMGjqx2"

Page({

  /**
   * 页面的初始数据
   */
  data: {

    data_duihua: "",
    access_token: "",
    neirong: "",
    name: "请选择精神状况",
    fileList: [],
    range: [{
        name: "心理健康良好"
      },
      {
        name: "轻度情绪波动"
      },
      {
        name: "中度心理压力"
      },
      {
        name: " 重度情绪困扰"
      },
      {
        name: '可能的认知衰退或老年痴呆症征兆'
      },
      {
        name: '需要紧急干预'
      }
    ],
    value: "",
    loading: true,
    serviceInfo: {},
    oldInfo: {},
    img: "",
    id: "",
    oldid: "",
    ist: false

  },

  onLoad(options) {
    this.getInfo(options.id);
    this.setData({
      id: options.id
    })
  },
  onChange(event) {
    // event.detail 为当前输入的值

    this.data.value = event.detail
  },
 
  toSubmit() {
    wx.navigateTo({
      url: '../formsubmit/formsubmit?oidid=' + this.data.oldid,
    })

  },
  //查询订单信息
  getInfo(id) {
    wx.cloud.callFunction({
      name: "order",
      data: {
        type: "selectById",
        id: id
      }


    }).then(res => {
      var id = res.result.data.pid
      var oldid = res.result.data.oldid
      this.setData({
        oldid: oldid
      })

      this.getServiceInfo(id)
      this.getOldInfo(oldid)
    })
  },


  getOldInfo(id) {
    wx.cloud.callFunction({
      name: "Oldman",
      data: {
        type: "selectById",
        id: id
      }
    }).then(res => {

      this.setData({
        oldInfo: res.result.data,
        loading: false

      })
    })
  },
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

  },
  submit() {
    console.log(this.data.ist)
    if (this.data.fileList.length == 0) {
      wx.showToast({
        title: '请上传合影',
        icon: "error"
      })
    } else if (!this.data.ist && this.data.serviceInfo.title == "上门健康检测") {

      wx.showToast({
        title: '请填写报告',
        icon: "error"
      })
    } else if (this.data.value == "" && this.data.serviceInfo.title == "上门心理测评") {
      wx.showToast({
        title: '请输入精神状况',
        icon: "error"
      })
    } else {

      const date = new Date();
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      var time = year + "/" + month + "/" + day;
      this.getSubmitX(time)

      var now = this.formatDate(date); // 输出: "2023-10-20 12:34:56"

      wx.cloud.callFunction({
        name: "order",
        data: {
          type: "wc",
          t: 2,
          id: this.data.id,
          img: this.data.fileList[0].url,
          wctime: now
        }

      }).then(res => {

        console.log(res)
        setTimeout(() => {
          wx.showToast({
            title: '订单完成',
          })
        }, 1000);
        wx.navigateBack()
      })
    }

  },
  getAccessToken(time) {
    let that = this
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + api_key + '&client_secret=' + secret_key,
      method: 'POST',
      'headers': {
        'Content-Type': 'application/json',
        'accept': 'application/json'
      },
      success: res => {
        console.log(res)
        that.setData({
          access_token: res.data.access_token
        })
        that.instrucModel(time)
      },
      fail: err => {
        //
      }
    })
  },
  instrucModel(time) {
    let that = this
    const access_token = that.data.access_token
    console.log(access_token)
    const url_chat = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=' + access_token
    const payload = {
      "messages": [{
        "role": "user",
        "content": "根据以下内容分析老人今日心理状况100字：" + that.data.neirong //问的问题
      }]
    };
    wx.showLoading({
      title: '生成中...',
    });
    wx.request({
      url: url_chat,
      method: "POST",
      data: payload,
      'header': {
        'Content-Type': 'application/json'
      },
      success: res => {
        console.log(res.data)
        that.setData({
          data_duihua: res.data.result
        })
        //上传今日精神状态
        var obj = {
          "up": this.data.value,
          "time": time,
          "ai": this.data.data_duihua
        }

        db.collection("oldmanlist").where({
          _id: this.data.oldid
        }).update({
          data: {
            mental: _.push(obj)
          }
        })
        wx.hideLoading();
      }
    })
  },
  getSubmitX(time) {
    if (this.data.serviceInfo.title == "上门心理测评") {
      this.getAccessToken(time)
      console.log(time);
    }
  },
  toShow(e) {
    var index = e.detail.value
    console.log(this.data.range[index])
    this.setData({
      name: this.data.range[index].name,
    })
  },
  // 从相册选取
  afterRead(event) {
    const {
      file
    } = event.detail;

    let suffix = /\.[^\.]+$/.exec(file.tempFilePath)[0];

    wx.cloud.uploadFile({
      // 指定上传到的云路径
      cloudPath: new Date().getTime() + suffix,
      // 指定要上传的文件的小程序临时文件路径
      filePath: file.tempFilePath,
      // 成功回调
      success: res => {
        console.log('上传成功', res.fileID)
        this.data.fileList.push({
          url: res.fileID
        })
        this.setData({
          fileList: this.data.fileList
        })
      }
    })
  },
  delete() {
    this.data.fileList.length = 0
    this.setData({
      fileList: this.data.fileList
    })
  },
  //查询服务信息
  getServiceInfo(id) {
    wx.cloud.callFunction({
      name: "service",
      data: {
        type: "selectById",
        id: id
      }
    }).then(res => {

      this.setData({
        serviceInfo: res.result.data,

      })
    })
  }
})